package qingxin.servlet.client.comment;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import qingxin.dao.NewsCommentDAO;
import qingxin.dao.UserDAO;
import qingxin.factory.DAOFactory;
import qingxin.servlet.admin.AdminServlet;
import qingxin.vo.NewsComment;
import qingxin.vo.User;

@WebServlet("/client/comment/getByNews")
public class ShowServlet extends AdminServlet{
	private static final long serialVersionUID = 1L;
	private NewsCommentDAO newsCommentDAO;
	private UserDAO userDAO;
	
	public ShowServlet(){
		super();
		newsCommentDAO = DAOFactory.getNewsCommentDAO();
		userDAO = DAOFactory.getUserDAO();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html; charset=utf-8");
    	response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		if(!verification(request)){
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		try{
			int newsID = Integer.parseInt(request.getParameter("nid"));
			
			NewsComment[] comments = newsCommentDAO.getByNewsID(newsID);
			JSONArray jsonComments = new JSONArray();
			for(NewsComment c : comments){
				JSONObject jsonComment = new JSONObject();
				User user = userDAO.getByID(c.getUserID());
				jsonComment.put("avatar", user.getAvatar());
				jsonComment.put("username", user.getUserName());
				jsonComment.put("comment", c.getContent());
				jsonComment.put("datetime", c.getDate());
				jsonComments.put(jsonComment);
			}
			JSONObject result = new JSONObject();
			result.put("comments", jsonComments);
			
			writer.println(result.toString());
			
			response.setStatus(HttpServletResponse.SC_OK);
		}
		catch(Exception e){
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			writer.println("{\"msg\":\"wrong\"}");
		}
		finally{
			writer.flush();
			writer.close();
		}
	}
}
